package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 *菜品管理接口
 */
@RestController("userDishController")
@Api(tags = "菜品浏览接口")
@Slf4j
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类ID查询菜品信息和口味数据
     */
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId) {

        //构造Redis 的key，规则：dish_分类ID
        String key = "dish_" + categoryId;
        //查询Redis 中是否存在菜品数据
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);

        if (dishVOList != null && dishVOList.size() > 0) {
            //如果存在，直接返回，不需要查询数据库
            log.info("菜品信息已存在Redis中");
            return Result.success(dishVOList);
        }
        //如果不存在，根据分类ID查询菜品数据，同时查询菜品口味数据，将数据保存到Redis
        log.info("根据分类ID查询菜品:{}", categoryId);
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//起售状态
        dishVOList = dishService.dishWithFlavor(dish);

        redisTemplate.opsForValue().set(key, dishVOList);
        return Result.success(dishVOList);
    }
}
